﻿using System.Text.RegularExpressions;
using YourLastOptionsDialog.Controls;

namespace YourLastOptionsDialog.ViewModels.Options
{
    /// <summary>
    /// A validator that uses a regular expression for validation.
    /// </summary>
    public class RegularExpressionValidator : IValidator
    {
        /// <summary>
        /// Gets or sets the regular expression used for validation.
        /// </summary>
        public string RegularExpression
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the validation error message.
        /// </summary>
        public string ValidationErrorMessage
        {
            get;
            set;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RegularExpressionValidator"/> class.
        /// </summary>
        /// <param name="regularExpression">The regular expression to use for validation.</param>
        /// <param name="validationErrorMessage">The validation error message.</param>
        public RegularExpressionValidator(string regularExpression, string validationErrorMessage)
        {
            RegularExpression = regularExpression;
            ValidationErrorMessage = validationErrorMessage;
        }

        #region Implementation of IValidator

        /// <summary>
        /// Validates the specified input and returns a <see cref="ValidationResult"/> with the outcome of the validation.
        /// </summary>
        /// <param name="input">The input value to validate.</param>
        /// <returns>
        /// The result of the validation.
        /// </returns>
        public virtual ValidationResult Validate(string input)
        {
            if (string.IsNullOrEmpty(RegularExpression))
            {
                return ValidationResult.Success;
            }

            var regex = new Regex(RegularExpression);
            var isValid = regex.IsMatch(input);
            if (!isValid)
            {
                return new ValidationResult(isValid, ValidationErrorMessage);
            }

            return ValidationResult.Success;
        }

        #endregion
    }
}
